package com.han.yuhannews.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.han.yuhannews.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class NewsDetailsActivity extends Activity {
	
	private ViewFlipper mNewsBodyFlipper;
	private LayoutInflater mNewsBodyInflater;
	private float mStartX;
	private int Count = 0;
	private int mNid = 0;
	private int mPosition = 0;
	private int mCursor;
	private ArrayList<HashMap<String, Object>> mNewsData;
	private TextView newsDetails;
	private ImageButton replyBtn, shareBtn, collectBtn;
	private String mNewString;
	private ProgressDialog pDialog;
	private AlertDialog.Builder aDialog;
	Button newsDetailsTitleBarCom, newsDetailsPrev, newsDetailsNext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newsdetails);
		newsDetailsPrev = (Button) findViewById(R.id.newsdetails_titlebar_previous);
		newsDetailsNext = (Button) findViewById(R.id.newsdetails_titlebar_next);
		newsDetailsTitleBarCom = (Button) findViewById(R.id.newsdetails_titlebar_comments);
		replyBtn = (ImageButton) findViewById(R.id.news_reply_img_btn);
		shareBtn = (ImageButton) findViewById(R.id.news_share_btn);
		collectBtn = (ImageButton) findViewById(R.id.news_collect_btn);
		TextView textView_titleBar = (TextView) findViewById(R.id.newsdetails_titlebar_title);

		// 获取传递信息
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		// 设置详细页新闻类别的标题
		String categoryName = bundle.getString("categoryTitle");
		textView_titleBar.setText(categoryName);
		mCursor = mPosition = bundle.getInt("position");
		// 获取bundle中的ArrayList集合
		Serializable serializable = bundle.getSerializable("newsData");
		mNewsData = (ArrayList<HashMap<String, Object>>) serializable;
		if (mPosition==0) {
			//点击到第一个新闻则上一页按钮不可见
			newsDetailsPrev.setVisibility(View.GONE);
		}
		// 加载外部布局，显示新闻详细
		initNewsBody(0);

	}

	/** 初始化新闻详细页的数据，以及各个按钮
	 * @param index 把新闻页面的View加载到下标为index的ViewFiliper中
	 * */
	private void initNewsBody(int index) {
		HashMap<String, Object> hashMap = mNewsData.get(mPosition);
		// 新闻回复个数
		newsDetailsTitleBarCom.setText(hashMap.get("newslist_item_comments")
				.toString() + "回复");
		// 获取新闻编号
		mNid = (Integer) hashMap.get("nid");
		// 加载外部布局文件，从集合中获取新闻的基础内容 ，调用网络获取详细新闻
		mNewsBodyInflater = getLayoutInflater();
		View newsBodyView = mNewsBodyInflater.inflate(R.layout.textview_news_body, null);
		// 新闻标题
		TextView newsTitle = (TextView) newsBodyView
				.findViewById(R.id.news_body_title);
		newsTitle.setText(hashMap.get("newslist_item_title").toString());
		// 新闻出处、时间
		TextView newsPtimeTextAndSouce = (TextView) newsBodyView
				.findViewById(R.id.news_body_ptime_source);
		newsPtimeTextAndSouce.setText(hashMap.get("newslist_item_source")
				.toString() + hashMap.get("newslist_item_ptime").toString());

		// 从网络获取新闻详细内容
		newsDetails = (TextView) newsBodyView
				.findViewById(R.id.news_body_details);
		loginNewsBody(mNid);

		// 将布局放入ViewFlipper中实现同一个activity中的翻页,使用方法中的形参
		mNewsBodyFlipper = (ViewFlipper) findViewById(R.id.news_body_flipper);
		mNewsBodyFlipper.addView(newsBodyView,index);

		// 注册监听
		onCliclListener listener = new onCliclListener();
		newsDetailsPrev.setOnClickListener(listener);
		newsDetailsNext.setOnClickListener(listener);
		replyBtn.setOnClickListener(listener);
		shareBtn.setOnClickListener(listener);
		collectBtn.setOnClickListener(listener);
		// 给新闻详细的 textView 触摸滑动监听事件
		newsDetails.setOnTouchListener(new NewsBodyOnTouchListener());

	}

	// 内部类作为监听者
	class onCliclListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.newsdetails_titlebar_previous:
				showPrevious();
				break;
			case R.id.newsdetails_titlebar_next:
				showNext();
				break;

			case R.id.news_reply_img_btn:

				Intent intent = new Intent(NewsDetailsActivity.this,
						CommentsActivity.class);
				startActivity(intent);
				break;
			case R.id.news_share_btn:

				break;
			case R.id.news_collect_btn:

				break;

			}
		}
	}

	/**
	 * 显示下一条新闻
	 */
	private void showNext() {
		// 判断是否是最后一屏
		if (mPosition < mNewsData.size() - 1) {
			// 设置下一屏动画
			mNewsBodyFlipper.setInAnimation(this, R.anim.push_left_in);
			mNewsBodyFlipper.setOutAnimation(this, R.anim.push_left_out);
			//两个按钮设置成可见
			newsDetailsPrev.setVisibility(View.VISIBLE);
			newsDetailsNext.setVisibility(View.VISIBLE);
			mPosition++;
			// 判断下一屏是否已经创建,从ViewFiliper中获取子页面的数量
			if (mPosition >= mNewsBodyFlipper.getChildCount()) {
				
				initNewsBody(mNewsBodyFlipper.getChildCount());
			}
			// 显示下一屏
			mNewsBodyFlipper.showNext();
		} else {
			newsDetailsNext.setVisibility(View.GONE);
		}
		//最后一页则不显示按钮
		System.out.println(mCursor + ";" + mPosition);
	}

	private void showPrevious() {
		if (mPosition > 0) {
			newsDetailsPrev.setVisibility(View.VISIBLE);
			newsDetailsNext.setVisibility(View.VISIBLE);
			mPosition--;
			// 记录当前新闻编号
			HashMap<String, Object> hashMap = mNewsData.get(mPosition);
			mNid = (Integer) hashMap.get("nid");
			if (mCursor > mPosition) {
				mCursor = mPosition;
				
				initNewsBody(0);
				System.out.println(mNewsBodyFlipper.getChildCount());
				mNewsBodyFlipper.showNext();// 显示下一页
			}
			mNewsBodyFlipper.setInAnimation(this, R.anim.push_right_in);// 定义下一页进来时的动画
			mNewsBodyFlipper.setOutAnimation(this, R.anim.push_right_out);// 定义当前页出去的动画
			mNewsBodyFlipper.showPrevious();// 显示上一页
		} else {
			//设置上一页不可见
			newsDetailsPrev.setVisibility(View.GONE);
		}
		System.out.println(mCursor + ";" + mPosition);
	}

	/**
	 * 触摸新闻左右滑动跳转到上一篇，下一篇
	 */
	class NewsBodyOnTouchListener implements OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			// 手指按下
			case MotionEvent.ACTION_DOWN:
				// 记录起始坐标
				mStartX = event.getX();
				break;
			// 手指抬起
			case MotionEvent.ACTION_UP:
				// 往左滑动
				if (event.getX() > mStartX) {
					showPrevious();
				}
				// 往右滑动
				else if (event.getX() < mStartX) {
					showNext();
				}
				break;
			}
			return true;
		}
	}

	/**
	 * 从服务器获取新闻详细内容
	 * 
	 * @param nid
	 *            新闻编号
	 * */
	public String loginNewsBody(int nid) {
		mNewString = "新闻内容加载失败";
		AsyncHttpClient client = new AsyncHttpClient();
		String url = "http://172.16.5.243:8080/web/getNews";
		RequestParams params = new RequestParams();
		params.put("nid", nid);
		client.setTimeout(6000);
		pDialog = ProgressDialog.show(this, "请稍等", "新闻正在加载中", true, true);
		client.get(url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				pDialog.dismiss();
				String retStr = new String(responseBody);

				try {
					JSONObject jsonObject = new JSONObject(retStr);
					int retCode = jsonObject.getInt("ret");
					if (0 == retCode) {
						JSONObject jsonData = jsonObject.getJSONObject("data");
						JSONObject jsonNews = jsonData.getJSONObject("news");
						mNewString = jsonNews.getString("body");
						Log.i("onSuccess", mNewString);
						newsDetails.setText(Html.fromHtml(mNewString));

					}

				} catch (JSONException e) {
					e.printStackTrace();

				}

			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				pDialog.dismiss();
				aDialog = new AlertDialog.Builder(NewsDetailsActivity.this);
				aDialog.setTitle("失败");
				aDialog.setMessage("网络连接异常");
				aDialog.setCancelable(false);
				aDialog.setNegativeButton("确定", null);
				aDialog.show();
			}

		});

		return mNewString;
	}

}
